﻿using System.Windows;
using System.Windows.Controls;

namespace RIBA.Helper
{
	//Silverlight 4 von Claudius Huber

	public class UpdateSourceOnKeystrokePasswordBox : DependencyObject
	{
		public static readonly DependencyProperty UpdateSourceOnChangeProperty;

		static UpdateSourceOnKeystrokePasswordBox()
		{
			UpdateSourceOnChangeProperty = DependencyProperty.RegisterAttached
				(
					"UpdateSourceOnChange",
					typeof(bool),
					typeof(UpdateSourceOnKeystrokePasswordBox),
					new PropertyMetadata(false, OnPropertyChanged)
				);
		}

		//Set
		public static bool GetUpdateSourceOnChange(DependencyObject obj)
		{
			return (bool)obj.GetValue(UpdateSourceOnChangeProperty);
		}

		//Get
		public static void SetUpdateSourceOnChange(UIElement element, bool val)
		{
			element.SetValue(UpdateSourceOnChangeProperty, val);
		}

		public static void OnPropertyChanged(DependencyObject obj, DependencyPropertyChangedEventArgs e)
		{
			var passwordBox = obj as PasswordBox;
			if (passwordBox == null)
				return;
			if ((bool)e.NewValue)
				passwordBox.PasswordChanged += OnPasswordChanged;
			else
				passwordBox.PasswordChanged -= OnPasswordChanged;
		}

		static void OnPasswordChanged(object sender, RoutedEventArgs e)
		{
			var txt = sender as PasswordBox;
			if (txt == null)
				return;
			var be = txt.GetBindingExpression(PasswordBox.PasswordProperty);
			if (be != null)
				be.UpdateSource();
		}
	}
}